//
//  PPContentViewViewController.m
//  PPCheckTool
//
//  Created by BenJim on 2019/4/5.
//

#import "PPContentViewViewController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "Reachability.h"
#import <WebKit/WebKit.h>
#import "PPBottomBarView.h"
#import "PPShowNoDataView.h"

@interface PPContentViewViewController ()<UIWebViewDelegate,UIAlertViewDelegate,PPBottomBarViewDelegate>

@property (nonatomic) Reachability *hostReachability; // host check

@property (nonatomic) Reachability *internetReachability; //net  check

@property (nonatomic, strong) UIWebView * webView;



@property (nonatomic, strong) PPShowNoDataView * errorView;

@property (assign, nonatomic) BOOL isLoadFinish; // is load

@property (assign, nonatomic) BOOL isLandscape;// is land

@property (strong,nonatomic) UIAlertView *alertView;//退出 确认 警告框


@property (nonatomic, strong) PPBottomBarView * bottomView;

@end

@implementation PPContentViewViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    //设置参数
    [self configContentViews];
}

//显示协议内容
- (void)configContentViews{
    
    [self.view addSubview:self.webView];
    
    [self.view addSubview:self.bottomView];
    
    
    self.bottomView.translatesAutoresizingMaskIntoConstraints = NO;
    
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;

     [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_webView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_webView)]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_bottomView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_bottomView)]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_webView]-0-[_bottomView(50)]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_webView,_bottomView)]];
    
    
    [self listenNetWorkingStatus];
    

    [self.view addSubview:self.errorView];
    
    self.errorView.hidden = YES;

    [self.errorView.loadBtn addTarget:self action:@selector(clickLoadAction) forControlEvents:UIControlEventTouchUpInside];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

}

- (void) clickLoadAction{
    //    self.activityIndicatorView.hidden = NO;
    [SVProgressHUD showWithStatus:@"正在加载"];
    self.errorView.hidden = YES;
    self.isLoadFinish = NO;
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.addressString]]];
    [self checkNetwork];
}

//是否 跳转到 别的 应用
-(void)openOtherAppWithUIWebView:(UIWebView *)webView{
    if ([webView.request.URL.absoluteString hasPrefix:@"https://itunes.apple.com"]//Appstore
        ||[webView.request.URL.absoluteString hasPrefix:@"itms-services://"])//iOS 网页安装协议
    {
        [[UIApplication sharedApplication] openURL:webView.request.URL];
    }else{
        if (![webView.request.URL.absoluteString hasPrefix:@"http"]) {
            NSArray *whitelist = [[[NSBundle mainBundle] infoDictionary] objectForKey : @"LSApplicationQueriesSchemes"];
            for (NSString * whiteName in whitelist) {
                NSString *rulesString = [NSString stringWithFormat:@"%@://",whiteName];
                if ([webView.request.URL.absoluteString hasPrefix:rulesString]){
                    [[UIApplication sharedApplication] openURL:webView.request.URL];
                }
            }
        }
    }
}

//只管 固定的几个 跳转
-(void)openSomeTheAppWithUIWebView:(UIWebView *)webView{
    
    
    if ([webView.request.URL.absoluteString hasPrefix:@"https://itunes.apple.com"]//Appstore
        ||[webView.request.URL.absoluteString hasPrefix:@"itms-services://"]//iOS 网页安装协议
        ||[webView.request.URL.absoluteString hasPrefix:@"weixin://"]//微信跳转
        ||[webView.request.URL.absoluteString hasPrefix:@"mqq://"])//QQ跳转
    {
        [[UIApplication sharedApplication] openURL:webView.request.URL];
    }
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    
    if ([[[UIDevice currentDevice]systemVersion]intValue ] >8) {
        
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
        
    }else{
        
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}



- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}

// 网页开始加载时调用
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD showWithStatus:@"正在加载"];
    self.isLoadFinish = NO;
    [self openOtherAppWithUIWebView:webView];
}

// 网页加载完成之后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
    self.isLoadFinish = YES;
}




// 网页加载失败时调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
   
        [SVProgressHUD dismiss];
        
        [SVProgressHUD showErrorWithStatus:@"加载失败..."];
    
        self.errorView.hidden = NO;
}


//检查网络
-(void)checkNetwork{
    self.hostReachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.hostReachability startNotifier];
    [self updateInterfaceWithReachability:self.hostReachability];
}



- (void)listenNetWorkingStatus{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 设置网络检测的站点
    NSString *remoteHostName = @"www.baidu.com";
    
    self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
    [self.hostReachability startNotifier];
    [self updateInterfaceWithReachability:self.hostReachability];
    
    self.internetReachability = [Reachability reachabilityForInternetConnection];
    [self.internetReachability startNotifier];
    [self updateInterfaceWithReachability:self.internetReachability];
    
}

- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    [self updateInterfaceWithReachability:curReach];
}

//当前网络类型
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
    switch (netStatus) {
        case 0://无网络
            //网页加载完成，突然断网，不显示 无网络提醒视图
            if (!self.isLoadFinish) {
                self.errorView.hidden = NO;
                [SVProgressHUD dismiss];
            }
            break;
            
        case 1://WIFI
            NSLog(@"ReachableViaWiFi----WIFI");
            break;
            
        case 2://蜂窝网络
            NSLog(@"ReachableViaWWAN----蜂窝网络");
            break;
            
        default:
            break;
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.webView stopLoading];
}


- (void)setAddressString:(NSString *)addressString{
    
    _addressString = addressString;
    
    if (addressString.length > 0) {
        
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:self.addressString]];
        
        [self.webView loadRequest:request];
    
    }
    
}

- (void)clickBottomWith:(NSInteger)type{
    
    switch (type) {
        case 0:{
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.addressString]]];

        }
            
            break;
        case 1:{
            [self.webView reload];

        }
            
            break;
        case 2:{
            if ([self.webView canGoForward]) {[self.webView goForward];}

        }
            
            break;
        case 3:{
            if ([self.webView canGoBack]) {[self.webView goBack]; }

        }
            
            break;
        default:
            break;
    }
    
}

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectZero];
        _webView.delegate = self;
    }
    return _webView;
}

-(PPBottomBarView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[PPBottomBarView alloc]initWithFrame:CGRectZero];
        _bottomView.deleagte = self;
    }
    return _bottomView;
}

- (PPShowNoDataView *)errorView{
    if (!_errorView) {
        _errorView = [[PPShowNoDataView  alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    return _errorView;
}

@end
